package gameam.data;

import gameam.business.*;
import java.sql.*;
import java.util.ArrayList;

public class DatabaseLoader implements BaseDataClass
{
	private MCBaseTest _test;
	
	public DatabaseLoader(String DB)
	{
		try
		{
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            String database = 
              "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="+DB+";";
			//System.out.println(database);
            Connection DBCon = DriverManager.getConnection(database, "", "");
			Statement DBstatement = DBCon.createStatement();
			ArrayList<MCBaseQuestion> questions = getQuestionsFromSQL(DBstatement);
			_test = new MCBaseTest(questions);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			_test = null;
		}
	}
	
	private ArrayList<MCBaseQuestion> getQuestionsFromSQL(Statement DBsta)
	{
		ArrayList<MCBaseQuestion> Questions = new ArrayList<MCBaseQuestion>();
		try
		{
			ResultSet res = DBsta.executeQuery("SELECT * FROM TBLQUESTIONS ORDER BY ID");
				  
			while (res.next()) 
			{
				MCBaseQuestion temp = new MCBaseQuestion(res.getString("Question"));
				Questions.add(temp);
			}
			res.close();
		}
		catch(Exception e)
		{
			System.out.println('2');
			return null;
		}
		
		try
		{
			ResultSet res2 = DBsta.executeQuery("SELECT * FROM TBLANSWERS");
			while (res2.next()) 
			{
				MCAnswer temp = new MCAnswer(res2.getInt("Mark"), res2.getString("Answer"));
				Questions.get(res2.getInt("QuestionID")-1).AddAnswer(temp);
			}
			res2.close();
		}
		
		catch(Exception e)
		{
			System.out.println('3');
			return null;
		}
		
		return Questions;	
	}
	
	
	
	public MCBaseTest getTest()
	{
		return _test;
	}
}